package com.toocms.jinjuhang.ui.mine.payment

import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.JsonUtils
import com.blankj.utilcode.util.StringUtils
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.toocms.ipaynow.Ipaynow
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.PaymentType
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.BankCardListData
import com.toocms.jinjuhang.data.flow.TimeToPayData
import com.toocms.jinjuhang.data.order_pay.AppCallbackData
import com.toocms.jinjuhang.data.order_pay.FyData
import com.toocms.jinjuhang.data.order_pay.FyMessageData
import com.toocms.jinjuhang.data.order_pay.IpaynowData
import com.toocms.jinjuhang.data.order_pay.IpaynowFengFuData
import com.toocms.jinjuhang.ui.mine.payment.bank.BankListFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.bus.event.SingleLiveEvent
import com.toocms.tab.pay.TabPay
import com.toocms.tab.pay.modle.PayRequest
import androidx.core.net.toUri
import com.toocms.jinjuhang.config.Constants.ThirdPartyInfo.WECHAT_APP_KEY


class PaymentModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    var alipay_type = 0
    var timer: Timer? = null
    var signid: String = ""
    val card_no = ObservableField("添加新卡并支付")
    val isShowWxCodeDialog = ObservableBoolean()
    val orderSn by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ORDER_SN, "") ?: ""
    }
    val sumObservableField by lazy {
        val content = bundle?.getString(Constants.BundleKey.KEY_PAYMENT_SUM, "00") ?: "00"
        ObservableField(content)
    }

    val showCodeEvent = SingleLiveEvent<String>();

    val timeObservableField = ObservableField<String>()

    val paymentTypeObservableField = ObservableField(PaymentType.BANK)

    val aliPaymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        paymentTypeObservableField.set(PaymentType.ALI)
    })
    val wechatPaymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        paymentTypeObservableField.set(PaymentType.WECHAT)
    })
    val bankPaymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        paymentTypeObservableField.set(PaymentType.BANK)
    })
    val bankSelectClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragmentForResult(BankListFgt::class.java, 0x1)
    })
    val balancePaymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        paymentTypeObservableField.set(PaymentType.BALANCE)
    })
    val nullBindingCommand = BindingCommand<BindingAction>(BindingAction {})
    val closeCommand = BindingCommand<BindingAction>(BindingAction {
        isShowWxCodeDialog.set(false)
    })

    val infoLongClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        ClipboardUtils.copyText(
            "余额充值方式（备注ID号或姓名电话）\n" + "1.对公账户\n" + "名称：华盟鲲鹏（天津）电子商务有限公司\n" + "账号：12050183045100000017\n" + "开户行：中国建设银行股份有限公司天津泰星支行\n" + "2.联系工作人员协助充值，联系电话：\n" + "13389052287 高老师\n" + "13389062539 陈老师 \n" + "15332163857 吴老师"
        )
        showToast("已复制到剪贴板")
    })

    val paymentClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (paymentTypeObservableField.get()) {
            PaymentType.WECHAT -> {
//                isShowWxCodeDialog.set(true)
//                showToast("请充值后选择余额支付");
//                wechatPayment()
//                wechatPayment_fengfu()
                wechatPayment_FY()
            }

            PaymentType.ALI -> {
                aliPaymentFY()
//                when (alipay_type) {
//                    2 -> aliPayment2()
//                    1 -> aliPaymentFY()
//                }

            }

            PaymentType.BALANCE -> {
                balancePayment()
            }

            PaymentType.BANK -> {
                ys_protocol_pay_apply()
            }

            else -> {}
        }
    })

    init {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(
            Urls.Flow.TIME_TO_PAY, params, resultClass = TimeToPayData::class.java, result = {
                timer?.cancel()
                timer = Timer((it.time ?: "0").toLong() * 1000L)
                timer?.start()
            })
        // 获取支付宝渠道
        requestData(
            Urls.OrderPay.ALIPAY_TYPE, mutableMapOf(), resultClass = String::class.java, result = {
                alipay_type = JsonUtils.getString(it, "status").toInt()
            })
        // 银行卡
        protocolList()
        // 银行卡支付回调验证
        Messenger.getDefault().register(this, Constants.MessengerToken.TOKEN_CODE2) {
            appCallback()
        }
        // 丰付
        Messenger.getDefault().register(
            this, Constants.MessengerToken.TOKEN_WXPAY_FENGFU_RESPONSE, String::class.java
        ) {
            appCallback()
        }
    }

    private fun wechatPayment() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(Urls.OrderPay.IPAYNOW, params, resultClass = IpaynowData::class.java, result = {
            val message = it.post_data ?: return@requestData
            Ipaynow().wechatPayment(ActivityUtils.getTopActivity() as Context, message) { _, _ ->
                appCallback()
            }
        })
    }

    private fun wechatPayment_fengfu() {
        var appid: String = ""
        var merchantCode: String = ""
        val api = WXAPIFactory.createWXAPI(getApplication(), appid)
        val req = WXLaunchMiniProgram.Req()
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(
            Urls.OrderPay.IPAYNOW_FENGFU,
            params,
            resultClass = IpaynowFengFuData::class.java,
            result = {
                req.userName = ""
                val sb = StringBuffer()
                sb.append("/payindex/payindex/payindex?")
                sb.append("merchantCode=").append(merchantCode).append("&")
                sb.append("token=").append(it.token).append("&")
                sb.append("requestFlag=APP&")
                sb.append("signature=").append(it.signature)
                req.path = sb.toString()
                api.sendReq(req)
            })
    }

    private fun wechatPayment_FY() {
        val api = WXAPIFactory.createWXAPI(getApplication(), WECHAT_APP_KEY)
        val req = WXLaunchMiniProgram.Req()
        req.userName = "gh_35e152b04df9"
        val sb = StringBuffer()
        sb.append("/pages/payment/payment?")
        sb.append("order_sn=").append(orderSn).append("&")
//                sb.append("token=").append(it.token).append("&")
        sb.append("pay_amounts=").append(sumObservableField.get())
        req.path = sb.toString()
        api.sendReq(req)

//        var merchantCode: String = ""
//        val params = mutableMapOf<String, String?>()
//        params["member_id"] = UserRepository.user.member_id
//        params["order_sn"] = orderSn
//        params["pay_type"] = "minip"
//        requestData(
//            Urls.OrderPay.FY_PAYMENT_WX,
//            params,
//            resultClass = IpaynowFengFuData::class.java,
//            result = {
//
//            })
    }

    private fun aliPayment() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(
            Urls.OrderPay.ALI_PAYMENT, params, resultClass = PayRequest::class.java, result = {
                TabPay.payV2(this, it) {
                    appCallback()
                }
            })
    }

    private fun aliPaymentFY() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        params["channel"] = "1"
        requestData(
            Urls.OrderPay.FY_PAYMENT_ALIPAY, params, resultClass = FyData::class.java, result = {
//                TabPay.payV2(this, it) {
//                    appCallback()
//                }
                val fyMessageData =
                    GsonUtils.fromJson(it.pay_data.message, FyMessageData::class.java)
                val intent = Intent(Intent.ACTION_VIEW, fyMessageData.order_info.toUri())
                ActivityUtils.startActivity(intent)
            })
    }

    private fun aliPaymentWB() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        params["channel"] = "1"
        requestData(
            Urls.OrderPay.WB_PAYMENT, params, resultClass = PayRequest::class.java, result = {
                TabPay.payV2(this, it) {
                    appCallback()
                }
            })
    }

    private fun aliPayment2() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(
            Urls.OrderPay.IPAYNOW_ALI, params, resultClass = IpaynowData::class.java, result = {
                val message = it.post_data ?: return@requestData
                Ipaynow().wechatPayment(
                    ActivityUtils.getTopActivity() as Context, message
                ) { _, _ ->
                    appCallback()
                }
            })
    }

    private fun balancePayment() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(Urls.OrderPay.BALANCE_PAY, params, resultClass = String::class.java, result = {
            appCallback()
        })
    }

    override fun onStop() {
        super.onStop()
        timer?.cancel()
    }

    private fun appCallback() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["order_sn"] = orderSn
        requestData(
            Urls.OrderPay.APP_CALLBACK,
            params,
            resultClass = AppCallbackData::class.java,
            result = {
                Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
                val bundle = Bundle()
                bundle.putString(Constants.BundleKey.KEY_POINTS, it.pay_points)
                startFragment(PaymentResultFgt::class.java, bundle, true)
            })
    }

    private fun protocolList() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        requestData(
            Urls.Center.PROTOCOL_LIST,
            params,
            resultClass = BankCardListData::class.java,
            result = {
                if (CollectionUtils.isNotEmpty(it.list)) {
                    signid = it.list[0].signid.toString()
                    card_no.set(it.list[0].card_no)
                }
            },
            error = {})
    }

    private fun ys_protocol_pay_apply() {
        val params = mutableMapOf<String, String?>()
        params["signid"] = signid
        params["order_sn"] = orderSn
        params["member_id"] = UserRepository.user.member_id
        requestData(
            "OrderPay/ys_protocol_pay_apply",
            params,
            resultClass = String::class.java,
            isShowLoading = true,
            result = {
                showCodeEvent.postValue(JsonUtils.getString(it, "trade_no"))
            },
            error = {})
    }

    //------------------------------------------------内部类-----------------------------------------

    inner class Timer(countTime: Long) : CountDownTimer(
        countTime, Constants.Extra.COUNT_DOWN_INTERVAL
    ) {
        override fun onTick(millisUntilFinished: Long) {
            timeObservableField.set("${StringUtils.getString(R.string.str_remaining_time_of_payment)}${millisUntilFinished / (60 * 1000L)}:${millisUntilFinished % (60 * 1000L) / 1000L}")
        }

        override fun onFinish() {
            this@PaymentModel.finishFragment()
        }

    }

}